import axios from 'axios'
import {
  Toast
} from 'vant'
import store from '@/store/index.js'
import router from '../router'
import {
  authorizationsPut
} from '@/api/user.js'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})
//请求拦截
_axios.interceptors.request.use(config => {
    if (!config.noToken) {
      //请求头携带token
      config.headers.Authorization = `Bearer ${store.getters['user/getToken']}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
//相应拦截
_axios.interceptors.response.use(
  res => {
    return res.data
  },
  async error => {

    //401处理,获取新的token参数叫refresh_token
    if (error.response.status === 401) {
      try {
        //如果刷新token出错了就按以前方式处理
        const resToken = await authorizationsPut()
        console.log('refresh_token', resToken);
        //存储token
        store.commit('user/setToken', resToken.data.token)
        //让以前的处理正常进行
        return _axios(error.config)
      } catch {
        if (error.response.data && error.response.data.message && !error.config.noError) {
          Toast.fail(error.response.data.message)
        }
      }
      //删除token
      store.commit('user/setToken', '')
      //跳转登入页router。currentRouter当前路由信息
      router.push('/login?redirect=' + router.currentRoute.fullPath)
    } else {
      if (error.response.data && error.response.data.message && !error.config.noError) {
        Toast.fail(error.response.data.message)
      }
    }
    return Promise.reject(error)
  }
)
export default _axios
